package com.gallsoft.amidar;

import android.view.KeyEvent;

public class InputGameInterface extends BaseObject {
    private final static float KEY_FILTER = 0.25f;

    private InputXY mDirectionalPad = new InputXY();
	private InputButton mJumpButton = new InputButton();

	private int mLeftKeyCode = KeyEvent.KEYCODE_DPAD_LEFT;
	private int mRightKeyCode = KeyEvent.KEYCODE_DPAD_RIGHT;
	private int mDownKeyCode = KeyEvent.KEYCODE_DPAD_DOWN;
	private int mUpKeyCode = KeyEvent.KEYCODE_DPAD_UP;
	private int mJumpKeyCode = KeyEvent.KEYCODE_SPACE;
	private float mMovementSensitivity = 1.0f;
	
	@Override
	public void reset() {
		mJumpButton.release();
		mDirectionalPad.release();
	}

    public void update(float timeDelta, BaseObject parent) {
		InputSystem input = sSystemRegistry.inputSystem;
		final InputButton[] keys = input.getKeyboard().getKeys();
		
		final InputButton left = keys[mLeftKeyCode];
		final InputButton right = keys[mRightKeyCode];
		final InputButton up = keys[mUpKeyCode];
		final InputButton down = keys[mDownKeyCode];
		final float leftPressedTime = left.getLastPressedTime();
		final float rightPressedTime = right.getLastPressedTime();
		final float upPressedTime = up.getLastPressedTime();
		final float downPressedTime = down.getLastPressedTime();
		
		float xMagnitude = 0.0f;
		float yMagnitude = 0.0f;
		float pressTime = 0.0f;
		
		// left and right are mutually exclusive
		if (leftPressedTime > rightPressedTime) {
			xMagnitude = -left.getMagnitude() * KEY_FILTER * mMovementSensitivity;
			pressTime = leftPressedTime;
		} 
		else {
			xMagnitude = right.getMagnitude() * KEY_FILTER * mMovementSensitivity;
			pressTime = rightPressedTime;
		}
		
		// up and down are mutually exclusive
		if (upPressedTime > downPressedTime) {
			yMagnitude = -up.getMagnitude() * KEY_FILTER * mMovementSensitivity;
			pressTime = upPressedTime;
		} 
		else {
			yMagnitude = down.getMagnitude() * KEY_FILTER * mMovementSensitivity;
			pressTime = downPressedTime;
		}
		
		if (xMagnitude != 0.0f || yMagnitude != 0.0f) {
			mDirectionalPad.press(pressTime, xMagnitude, yMagnitude);
		} 
		else {
			mDirectionalPad.release();
		}

		final InputButton jumpKey = keys[mJumpKeyCode];

		if (jumpKey.getPressed()) {
			mJumpButton.press(jumpKey.getLastPressedTime(), jumpKey.getMagnitude());
		} 
		else {
			mJumpButton.release();
		}
    }
    
	public final InputXY getDirectionalPad() {
		return mDirectionalPad;
	}
	
	public final InputButton getJumpButton() {
		return mJumpButton;
	}

	public void setKeys(int left, int right, int jump, int attack) {
		mLeftKeyCode = left;
		mRightKeyCode = right;
		mJumpKeyCode = jump;
	}
	
	public void setMovementSensitivity(float sensitivity) {
		mMovementSensitivity  = sensitivity;
	}
}
